﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using DotConferenceSql;
using System.Data.SqlClient;
using NUnit.Framework.SyntaxHelpers;
using System.Data;

namespace TestDotConferenceSql
{

    [TestFixture]
    public class TestInsertIntoQueryElement
    {
        SqlQuery query;
        InsertIntoQueryElement insertElement;

        [SetUp]
        public void Init()
        {
            query = new SqlQuery();
            insertElement = new InsertIntoQueryElement();
        }

        [Test]
        public void BasicInsertQuery()
        {
            insertElement.Table = "Test";

            insertElement.Add("field1", 1);
            insertElement.Add("field2", "String");
            insertElement.Add("field3", true);
            insertElement.Add("field4", DateTime.Parse("2009-01-01"));

            query.Elements.Add(insertElement);

            Assert.That(query.BuildTextQuery(), Text.Contains("INSERT INTO Test(field1,field2,field3,field4) VALUES(@field1,@field2,@field3,@field4)"));

            List<SqlParameter> parameters = query.ListParameters();

            Assert.That(parameters.Count, Is.EqualTo(4));

            Assert.That(parameters[0].DbType, Is.EqualTo(DbType.Int32));
            Assert.That(parameters[1].DbType, Is.EqualTo(DbType.String));
            Assert.That(parameters[2].DbType, Is.EqualTo(DbType.Boolean));
            Assert.That(parameters[3].DbType, Is.EqualTo(DbType.DateTime));
        }

        [Test]
        public void InsertQueryWithIdentity()
        {
            insertElement.Table = "Test";
            insertElement.AddIdentity("field1");
            insertElement.Add("field2", 1);

            query.Elements.Add(insertElement);

            Assert.That(query.BuildTextQuery(), Text.Contains("INSERT INTO Test(field1,field2) VALUES(SCOPE_IDENTITY(),@field2)"));

            Assert.That(query.ListParameters().Count, Is.EqualTo(1));
        }

        [Test]
        [ExpectedException(typeof(ArgumentException))]
        public void InsertQueryWithNoField()
        {
            insertElement.Table = "Test";

            query.Elements.Add(insertElement);

            query.BuildTextQuery();
        }

        [Test]
        [ExpectedException(typeof(ArgumentException))]
        public void InsertQueryWithNoTable()
        {
            insertElement.Add("field1", 1);

            query.Elements.Add(insertElement);

            query.BuildTextQuery();
        }
    }
}
